package com.rankeiot.developer.interceptor;

import com.rankeiot.core.Current;
import com.rankeiot.core.anno.interceptor.AuthInterceptor;
import com.rankeiot.core.data.UserInfo;
import com.rankeiot.core.exception.AuthException;
import com.rankeiot.core.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.model.Options;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletResponse;
import org.ssssssss.script.MagicScriptContext;

@Component
@RequiredArgsConstructor
public class APIRequestInterceptor implements RequestInterceptor {
    /**
     * 接口请求之前
     * @param info	接口信息
     * @param context	脚本变量信息
     */
    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context, MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {
        // 接口选项配置了需要登录
        if ("true".equals(info.getOptionValue(Options.ANONYMOUS))) {
            return null;
        }
        String token=request.getHeader("Token");
        if(StringUtil.isEmpty(token)){
             token=request.getHeader("Magic-Token");
        }
        if(StringUtil.isNotEmpty(token)){
            String keyName = "@user_key_";
            request.setAttribute(keyName,token);
        }
        UserInfo userInfo = Current.user();
        String userType=info.getOptionValue("user_type");
        char ut='U';
        if(StringUtil.isNotEmpty(userType)){
            ut=userType.charAt(0);
        }
        String role = info.getOptionValue(Options.ROLE);
        String permission = info.getOptionValue(Options.PERMISSION);
        String subTypes=info.getOptionValue("sub_type");
        if(subTypes==null){
            subTypes="";
        }
        try {
            AuthInterceptor.checkPriv(userInfo, ut, new String[]{role}, new String[]{permission}, subTypes.toCharArray());
        }catch (AuthException e){
            return new JsonBean<>(e.getCode(),e.getMessage());
        }
        return null;
    }
}
